<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html>
<%@include file="../base/frameBase.jsp" %>
<body>

<!-- 内容主体区域 -->
<div style="padding: 15px;width: 80%">
    <p id="title" style="font-size:22px"></p>
    <hr>
    <blockquote class="layui-elem-quote">为课程添加章节视频和标题说明</blockquote>
    <form class="layui-form" id="videoForm">

        <div class="layui-form-item">
            <label class="layui-form-label">视频标题</label>
            <div class="layui-input-block" style="width: 350px;">
                <input type="text" name="video_title" required lay-verify="required" placeholder="请输入视频名称（必填）"
                       autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">课程简介</label>
            <div class="layui-input-block">
                <textarea placeholder="请输入视频的简介内容（选填）" class="layui-textarea" style="width: 350px;"
                          name="video_desc"></textarea>
            </div>
        </div>

        <%--新增的--%>
        <div class="layui-upload">
            <p style="color: #FF5722">请上传视频类型的文件，其他文件无法通过验证，文件大小限制100M以内。</p>
            <div class="layui-upload-list">
                <table id="video-upd" class="layui-table" lay-size="sm" lay-skin="row">
                    <thead>
                    <tr>
                        <th>
                            <div class="layui-table-cell laytable-cell-2-status" align="center"><span>文件名</span></div>
                        </th>
                        <th>
                            <div class="layui-table-cell laytable-cell-2-status" align="center"><span>大小</span></div>
                        </th>
                        <th>
                            <div class="layui-table-cell laytable-cell-2-status" align="center"><span>状态</span></div>
                        </th>
                        <th>
                            <div class="layui-table-cell laytable-cell-2-status" align="center"><span>进度</span></div>
                        </th>
                        <th>
                            <div class="layui-table-cell laytable-cell-2-status" align="center"><span>操作</span></div>
                        </th>
                    </tr>
                    </thead>
                    <tbody id="imageListView"></tbody>
                </table>
            </div>
            <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" id="imageList"><i class="layui-icon">&#xe608;</i>添加附件
            </button>
            <button type="button" class="layui-btn layui-btn-xs" id="imageListAction"><i class="layui-icon">&#xe756;</i>开始上传
            </button>
        </div>

        <%--结束--%>
        <div class="layui-form-item" id="videores" type="hidden">
            <input type="hidden" name="video_url" id="videou">
        </div>

        <div class="layui-form-item submit">
            <div class="layui-input-block">
                <button class="layui-btn layui-btn-warm" lay-submit lay-filter="formDemo">增加章节</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置表单</button>
            </div>
        </div>
        <hr>
    </form>

    <script type="text/html" id="barTool">
        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="play">播放视频</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>
    <p style="font-size:22px">当前课程视频列表</p>
    <table class="layui-hide" id="videos" lay-filter="course"></table>

</div>


<script>
    layui.use(['upload', 'form', 'layer', 'element', 'table'], function () {
        var upload = layui.upload;
        var $ = layui.jquery;
        var form = layui.form;
        var layer = layui.layer;
        var element = layui.element;
        var table = layui.table;

        var theRequest = new Object();
        // 加载url参数
        var url = location.search; //获取url中"?"符后的字串
        url = decodeURI(url);
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        }
        console.log(theRequest);
        $('#title').html('当前编辑的课程为：<b>' + theRequest.title + '</b>');


        $("#videores").hide();
        //创建监听函数
        var xhrOnProgress = function (fun) {
            xhrOnProgress.onprogress = fun; //绑定监听
            //使用闭包实现监听绑
            return function () {
                //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
                var xhr = $.ajaxSettings.xhr();
                //判断监听函数是否为函数
                if (typeof xhrOnProgress.onprogress !== 'function')
                    return xhr;
                //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
                if (xhrOnProgress.onprogress && xhr.upload) {
                    xhr.upload.onprogress = xhrOnProgress.onprogress;
                }
                return xhr;
            }
        };

        var imageListView = $('#imageListView')
            , alreadyUploadFiles = {}//记录已经上传成功的文件相对路径（后台返回）
            , maxNumber = 1//这里设置自己允许最大上传数
            , uploadListIns = upload.render({
            elem: '#imageList'
            , url: '${ctx}/videoData/uploadVideo'//这里设置自己的上传接口
            , accept: 'video'
            , multiple: true
            , auto: false
            , size: 102400
            , number: maxNumber
            , bindAction: '#imageListAction'
            , xhr: xhrOnProgress
            , progress: function (index, value) {//上传进度回调 value进度值
                element.progress('image' + index, value + '%');//设置页面进度条
            }
            , errorMsg: function (content) {
                layer.msg(content, {icon: 2, shift: 6});
            }
            , choose: function (obj) {
                var that = this;
                //检查是否已经成功上传了maxNumber个视频
                //获取上传成功的文件：
                var alreadyUploadFilesLength = Object.keys(alreadyUploadFiles).length;
                if (alreadyUploadFilesLength >= maxNumber) {
                    that.errorMsg('同时最多只能上传的数量为：' + maxNumber);
                    return false;
                }
                //读取本地文件
                obj.preview(function (index, file, result) {
                    var files = that.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                    var alreadyChooseFileLength = 0;
                    if (that.files) {//已经选择，未上传的文件
                        $.each(that.files, function () {
                            alreadyChooseFileLength++;
                        })
                    }
                    if ((alreadyUploadFilesLength + alreadyChooseFileLength) > maxNumber) {
                        that.errorMsg('同时最多只能上传的数量为：' + maxNumber);
                        delete that.files[index];
                        delete files[index];
                        uploadListIns.config.elem.next()[0].value = '';
                        return false;
                    }

                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td class="name"><a class="upload-img-prev-link">' + file.name + '</a></td>'
                        , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                        , '<td id="status-upd">等待上传</td>'
                        , '<td>'
                        , '<div class="layui-progress layui-progress-big layui-progress-radius-fix" lay-showpercent="true" lay-filter="image' + index + '">'
                        , '<div class="layui-progress-bar" lay-percent="0%">'
                        , '<span class="layui-progress-text">0%</span>'
                        , '</div>'
                        , '</div>'
                        , '</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-mini image-reload layui-hide">重传</button>'
                        , '<div class="layui-btn layui-btn-sm layui-btn-danger image-delete">删除</div>'
                        , '</td>'
                        , '</tr>'].join(''))

                    //单个重传
                    tr.find('.image-reload').on('click', function () {
                        obj.upload(index, file);
                    });
                    //  删除按钮
                    tr.find('.image-delete').on('click', function () {
                        if ($('#status-upd').text() == '等待上传') {
                            // 删除表格附件样式
                            var tb = document.getElementById('video-upd');
                            var rowNum = tb.rows.length;
                            for (i = 1; i < rowNum; i++) {
                                tb.deleteRow(i);
                                rowNum = rowNum - 1;
                                i = i - 1;
                            }
                            // 清空文件队列
                            delete that.files[index];
                            delete files[index];
                            uploadListIns.config.elem.next()[0].value = '';
                        } else {
                            console.log(index)
                            console.log(file)
                            var data = {};
                            data.filename = $('#videou').val();
                            // 提交删除文件请求
                            $.ajax({
                                url: '${ctx}/videoData/deleteVideoFile',
                                method: 'post',
                                contentType: 'application/json',
                                data: JSON.stringify(data), // 以json字符串方式传递
                                success: function (data) {
                                    console.log(data)
                                    if (data.code != '00000') {
                                        layer.msg('[删除失败,请重试]');
                                    } else {
                                        layer.msg("删除附件成功");
                                        // 清空table附件
                                        resetTb();
                                    }
                                },
                                error: function (data) {
                                    alert("信息发送失败，请检查网络连接。");
                                }
                            })
                        }
                    });
                    imageListView.append(tr);
                })
                ;
            },
            done: function (res, index, upload) {
                if (res.code == 0) { //上传成功
                    var tr = imageListView.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).find('.layui-progress-bar').css('background-color', '#86EAA1');

                    alreadyUploadFiles[index] = res.data && res.data[0];//缓存已上传的文件

                    console.log(res.data);
                    $("#videores").show();
                    $("#videourl").text(res.data);
                    $("#videou").val(res.data);
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
            ,
            error: function (index, upload) {
                var tr = imageListView.find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #ff5722;">上传失败</span>');
                tds.eq(3).find('.layui-progress-bar').css('background-color', '#ff5722');
                tds.eq(4).find('.image-reload').removeClass('layui-hide'); //显示重传
            }
        });

        var resetTb = function () {
            var tb = document.getElementById('video-upd');
            var rowNum = tb.rows.length;
            for (i = 1; i < rowNum; i++) {
                tb.deleteRow(i);
                rowNum = rowNum - 1;
                i = i - 1;
            }
            // 手动将hidden的input表单数据重置
            $('#videou').val('');
            for (var key in alreadyUploadFiles) {
                delete alreadyUploadFiles[key];
            }
        }

        form.on('submit(formDemo)', function (data) {
            if (theRequest.cid != '') {
                data.field['cid'] = theRequest.id;
            } else {
                layer.msg("课程信息无法获取，请检查网络或登录状态。");
                return false;
            }
            delete data.field.file;
           // alert(JSON.stringify(data.field));

            $.ajax({
                url: '${ctx}/videoData/addVideo',
                method: 'post',
                contentType: 'application/json',
                data: JSON.stringify(data.field), // 以json字符串方式传递
                success: function (data) {
                    console.log(data)
                    if (data.code != '00000') {
                        layer.msg('[上传失败]' + data.msg);
                    } else {
                        layer.msg("上传成功");
                        // 清空table附件
                        resetTb();
                        //清空表单数据
                        $(':input', '#videoForm')
                            .not(':button, :submit, :reset, :hidden')
                            .val('')
                            .removeAttr('checked')
                            .removeAttr('selected');
                        // 刷新下视频数据表格
                        table.reload('tableReload', {
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                            , where: {
                                cid: courseId
                            }
                        });
                    }
                },
                error: function (data) {
                    alert("信息发表失败，请检查网络连接。");
                }
            });
            return false;
        });

        var courseId = theRequest.id,
            table = table.render({
                elem: '#videos'
                , url: '${ctx}/videoData/getVideosByCid'
                , cols: [[
                    {field: 'video_title', title: '视频标题', width: 170}
                    , {field: 'video_desc', title: '视频简介', width: 200}
                    , {field: 'video_url', title: '链接地址', width: 380}
                    , {field: 'createTime', title: '上传时间', width: 200}
                    , {field: 'state', title: '状态', width: 70}
                    , {fixed: 'right', title: '操作', width: 200, align: 'center', toolbar: '#barTool'}
                ]]
                , id: 'tableReload'
                , page: true
                , height: 500
                , where: {
                    cid: courseId
                }
            })

        //监听表格复选框选择
        this.table.on('checkbox(course)', function (obj) {
            console.log(obj)
        });
        //监听工具条
        this.table.on('tool(course)', function (obj) {
            var data = obj.data;
            if (obj.event === 'play') {
                // layer.msg('ID：' + data.id + ' 的查看操作');
                // 播放视频
                layer.open({
                    type: 1,
                    title: data.video_title,
                    skin: 'layui-layer-rim', //加上边框
                    area: ['740px', '450px'],
                    content: '<div class="m">' +
                    '<video id="my-video" class="video-js" controls preload="auto" width="740px" height="400px" data-setup="{}">' +
                    '<source src="' + data.video_url + '" type="video/mp4"></video>' +
                    '<script src="${ctx}/static/js/video/video.min.js" type="text/javascript" charset="utf-8"><\/script>' +
                    '<script type="text/javascript">var myPlayer = videojs(\'my-video\');' +
                    'videojs("my-video").ready(function(){' +
                    'var myPlayer = this;' +
                    'myPlayer.play();});' +
                    '<\/script></div>'
                });

            } else if (obj.event === 'del') {
                var data = obj.data
                // 删除课程下的视频按钮
                layer.confirm('确定删除该视频吗，该操作不可撤销！删除视频标题为：' + data.video_title, function (index) {
                    obj.del();
                    layer.close(index);
                    // 发起后台删除借口请求
                    $.ajax({
                        url: '${ctx}/videoData/deleteVideo',
                        method: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(data), // 以json字符串方式传递
                        success: function (data) {
                            if (data.code != '00000') {
                                layer.msg('[删除失败]' + data.msg);
                            } else {
                                layer.msg("删除成功！");
                                // 清空table附件
                                resetTb();
                                //清空表单数据
                                $(':input', '#videoForm')
                                    .not(':button, :submit, :reset, :hidden')
                                    .val('')
                                    .removeAttr('checked')
                                    .removeAttr('selected');
                                // 刷新下视频数据表格
                                table.reload('tableReload', {
                                    page: {
                                        curr: 1 //重新从第 1 页开始
                                    }
                                    , where: {
                                        cid: courseId
                                    }
                                });
                            }
                        },
                        error: function (data) {
                            alert("信息发表失败，请检查网络连接。");
                        }
                    })
                });
            }
        });
        var active = {
            reload: function () {
                //执行重载 会重新请求后台端口，搜索
                table.reload('tableReload', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: {
                        cid: courseId
                    }
                });
                console.log("reload suc")
            }
        };

        $('.demoTable .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
    });
</script>
<%@include file="../base/frameFoot.jsp" %>